<template>
  <div class="add-or-edit">
    <Button type="primary" @click="handleClick">{{ isEdit?'编辑':'新增' }}</Button>
    <el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="isEdit?'编辑':'新增'">
      <FormContainer :column="2">
        <el-form ref="form" :model="formData" :rules="formRules" :close-on-click-modal="false" label-width="120px">
          <el-form-item label="购买渠道" prop="channel">
            <SelectForDict :code.sync="formData.channel" :name.sync="formData.channelName" dict-type-code="PURCHASE_CHANNEL" placeholder="请选择购买渠道" clearable filterable @update:code="handleChannelChange"></SelectForDict>
          </el-form-item>
          <el-form-item label="一级业务类型" prop="businessType">
            <SearchSelectPicker
              placeholder="请选择一级业务类型"
              lable-name="businessTypeName"
              value-name="businessType"
              :parent-id="formData.channel"
              must-pid
              :disabled="formData.channel===''||formData.channel===undefined"
              method="get"
              :url="`/call-center/api/v2/channelBusinessRelation/queryBusiness/${formData.channel}`"
              :value.sync="formData.businessType"
              :lable.sync="formData.businessTypeName"
              @selectChange="handleSelectChange"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item label="二级业务类型" prop="businessTypeTwo">
            <SearchSelectPicker
              placeholder="请选择二级业务类型"
              lable-name="businessTypeTwoName"
              value-name="businessTypeTwo"
              :parent-id="secondBTpe"
              :disabled="!secondBTpe"
              must-pid
              method="get"
              :url="`/call-center/api/v2/channelBusinessRelation/queryBusinessTwo/${formData.channel}/${formData.businessType}`"
              :value.sync="formData.businessTypeTwo"
              :lable.sync="formData.businessTypeTwoName"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item label="原因类型" prop="workCaseType">
            <SelectForDict :code.sync="formData.workCaseType" :name.sync="formData.workCaseTypeDesc" dict-type-code="REASON_TYPE" placeholder="请选择原因类型" clearable filterable @on-change="handleOnChange"></SelectForDict>
          </el-form-item>
          <el-form-item label="工单原因" prop="workCaseValue">
            <SearchSelectPicker
              placeholder="请选择工单原因"
              lable-name="dictName"
              value-name="dictCode"
              :parent-id="formData.workCaseTypeId"
              :disabled="!formData.workCaseTypeId"
              must-pid
              method="get"
              :url="`/data-dict/api/v2/dictionary/child`"
              :params="{
                type: 1,
                query: {
                  parentDictId: formData.workCaseTypeId
                }
              }"
              :value.sync="formData.workCaseValue"
              :lable.sync="formData.workCaseValueDesc"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item label="处理方案" prop="handleScheme">
            <SelectForDict :code.sync="formData.handleScheme" :name.sync="formData.handleSchemeName" dict-type-code="PROCESS_METHOD" placeholder="请选择处理方案" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item prop="dealerPostCode" label="处理人岗位">
            <SelectForDict :code.sync="formData.dealerPostCode" :name.sync="formData.dealerPostName" dict-type-code="DEPT_POST_CODE" placeholder="请选择处理人岗位" clearable filterable></SelectForDict>
          </el-form-item>
          <!-- <el-form-item prop="complaintObject" label="被投诉对象">
            <SelectForDict :code.sync="formData.complaintObject" :name.sync="formData.complaintObjectName" dict-type-code="OBJECT_OF_COMPLAINT" placeholder="请选择被投诉对象" clearable filterable></SelectForDict>
          </el-form-item> -->
          <!-- <el-form-item prop="agingTreatment" label="时效">
            <el-input v-model="formData.agingTreatment" number placeholder="请输入时效">
              <template slot="append">小时</template>
            </el-input>
          </el-form-item> -->
          <el-form-item prop="includeCreator" label="是否包含创建人">
            <SearchSelectPicker
              placeholder="请选择是否包含创建人"
              lable-name="dictName"
              value-name="dictCode"
              :select-data="whetherList"
              :value.sync="formData.includeCreator"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="ccPostCode" label="抄送岗位">
            <SelectForDict :code.sync="formData.ccPostCode" :name.sync="formData.ccPostName" dict-type-code="DEPT_POST_CODE" placeholder="请选择抄送岗位" clearable filterable></SelectForDict>
          </el-form-item>
          <el-form-item :span="24">
            <div style="text-align: right;">
              <Button type="default" @click="handleCancel">取消</Button>
              <Button type="primary" @click="handleSave">保存</Button>
            </div>
          </el-form-item>
        </el-form>
      </FormContainer>
    </el-dialog>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import SelectForDict from '@/components/SelectForDict'
import SearchSelectPicker from '@/components/SearchSelectPicker'
import { create, update } from '@/api/distributionLogicConfig'
export default {
  name: 'AddOrEdit',
  components: {
    FormContainer,
    SelectForDict,
    SearchSelectPicker
  },
  props: {
    selection: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // const validatorAgingTreatment = (r, v, c) => {
    //   if (v === '' || v === undefined) {
    //     c(new Error('请填写时效'))
    //   } else {
    //     c()
    //   }
    // }
    // eslint-disable-next-line no-unused-vars
    const validatorIncludeCreator = (r, v, c) => {
      if (v === '' || v === undefined) {
        c(new Error('请选择处理人是否包含创建人'))
      } else {
        c()
      }
    }
    return {
      whetherList: [
        { dictCode: '0', dictName: '否' },
        { dictCode: '1', dictName: '是' }
      ],
      visible: false,
      formData: {
        // agingTreatment: '', // 时效
        businessType: '', // 业务类型1
        businessTypeName: '', // 业务类型1名称
        businessTypeTwo: '', // 业务类型2
        businessTypeTwoName: '', // 业务类型2名称
        channel: '', // 渠道编码
        channelName: '', // 渠道名称
        // complaintObject: '', // 被投诉对象
        // complaintObjectName: '', // 被投诉对象名称
        handleScheme: '', // 处理方案
        handleSchemeName: '', // 处理方案名称
        workCaseType: '',
        workCaseTypeDesc: '',
        workCaseTypeId: '',
        workCaseValue: '',
        workCaseValueDesc: '',
        includeCreator: '0', // 处理人是否包含创建人
        ccPostCode: '',
        ccPostName: '',
        dealerPostCode: '',
        dealerPostName: ''
      },
      formRules: {
        //  // agingTreatment: [{ required: true, validator: validatorAgingTreatment, trigger: 'change' }],
        // businessType: [{ required: true, message: '请选择一级业务类型', trigger: 'change' }],
        // businessTypeTwo: [{ required: true, message: '请选择二级业务类型', trigger: 'change' }],
        // channel: [{ required: true, message: '请选择购买渠道', trigger: 'change' }],
        // handleScheme: [{ required: true, message: '请选择处理方案', trigger: 'change' }],
        // workCaseType: [{ required: true, message: '请选择原因类型', trigger: 'change' }],
        // workCaseValue: [{ required: true, message: '请选择工单原因', trigger: 'change' }],
        // includeCreator: [{ required: true, validator: validatorIncludeCreator, trigger: 'change' }],
        //  // ccPostCode: [{ required: true, message: '请选择抄送岗位', trigger: 'change' }],
        // dealerPostCode: [{ required: true, message: '请选择处理人岗位', trigger: 'change' }]
        //  // complaintObject: [{ required: true, message: '请选择被投诉对象', trigger: 'change' }]
      }
    }
  },
  computed: {
    detail() {
      return this.isEdit && this.selection instanceof Array && this.selection.length > 0 ? this.selection[0] : {}
    },
    secondBTpe() {
      const t = this.formData
      const t1 = t.channel !== undefined && t.businessType !== undefined && t.channel !== '' && t.businessType !== ''
      return t1 ? `${t.channel}-${t.businessType}` : undefined
    }
  },
  watch: {
    visible: {
      handler(v) {
        if (v) {
          if (this.isEdit) {
            for (const k of Object.keys(this.formData)) {
              const v = this.detail[k]
              this.$set(this.formData, k, v === undefined ? '' : v)
            }
          }
        } else {
          const form = this.$refs.form
          form && form.resetFields()
        }
      },
      immediate: true
    }
  },
  methods: {
    handleChannelChange() {
      this.$set(this.formData, 'businessType', '')
      this.$set(this.formData, 'businessTypeName', '')
      this.$set(this.formData, 'businessTypeTwo', '')
      this.$set(this.formData, 'businessTypeTwoName', '')
    },
    handleSelectChange() {
      this.$set(this.formData, 'businessTypeTwo', '')
      this.$set(this.formData, 'businessTypeTwoName', '')
    },
    handleOnChange(data) {
      if (data) {
        this.$set(this.formData, 'workCaseTypeId', data.dictId)
      } else {
        this.$set(this.formData, 'workCaseTypeId', '')
      }
      this.$set(this.formData, 'workCaseValue', '')
      this.$set(this.formData, 'workCaseValueDesc', '')
    },
    handleClick() {
      if (this.isEdit) {
        if (this.selection.length > 1) {
          this.$message.warning(`该操作只能单选`)
          return
        } else if (this.selection.length === 0) {
          this.$message.warning(`请选择【编辑】项`)
          return
        }
      }
      this.visible = true
    },
    handleCancel() {
      this.visible = false
    },
    handleSave() {
      return this.$refs.form.validate().then(() => {
        return this.saveData()
      })
    },
    saveData() {
      const ajax = this.isEdit ? update : create
      const data = {}
      if (this.isEdit) {
        Object.assign(data, this.detail)
      }
      Object.assign(data, this.formData)
      return ajax(data).then(res => {
        this.$message.success('操作成功!')
        this.visible = false
        this.$emit('on-refresh', this.isEdit ? 'onPage' : 'opCondition')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.add-or-edit{
  display: inline-block;
  margin-right: 10px;
}
</style>
